<!--
 @description 搭配效果图
 @fileName RenderImage.vue
 @author zengqiongying
 @created 2024/08/20 15:08:00
-->
<template>
  <div>
    <div class="table-title">
      <span class="c-red">*</span>搭配效果图：
      <div v-if="list.length<limit" class="title-btns">
        <UploadLocalImge @change="getLocalImageBase" @getFile="getLocalImageFile" />
        <!-- <el-button type="primary" size="mini" @click="handleOpenUpload">本地上传图片</el-button> -->
        <select-programme-pic
          ref="schemeImg"
          :scheme-id="schemeId"
          :combine-id="combineId"
          @change="handleSaveSchemeImage"
        />
        <div v-if="list.length" style="margin-left: 10px;color:#999">可拖动图片进行排序,最多可{{ limit }}张</div>
      </div>
    </div>
    <div class="pic-list">
      <div v-for="(item,i) in list" :key="`${i}_${item.id}`" class="pic-wrap">
        <el-image :src="getImageUrl(item)" :preview-src-list="previewSrcList" fit="contain" />
        <div class="opt">
          <div v-if="[1,'1'].includes(item.isMainPic)" class="tag">封面图</div>
          <div v-else class="btn-cover" @click="handleSetCover(item)">设为封面图</div>
          <div class="btn-del" @click="handleDelete(item)">删除</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import SelectProgrammePic from './SelectProgrammePic.vue'
import UploadLocalImge from './UploadLocalImge'
import Sortable from 'sortablejs'
import { uploadFile, setCoverImage, saveRendering, deleteRendering, updateImageSort } from '@/api/productCombine/scheme'
export default {
  name: 'RenderImage',
  components: { UploadLocalImge, SelectProgrammePic },
  props: {
    combineId: {
      type: String,
      default: ''
    },
    schemeId: {
      type: String,
      default: ''
    },
    list: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      adsImgHost: process.env.VUE_APP_ADS_STATIC,
      sadImgHost: process.env.VUE_APP_Img_prefix,
      limit: 20,
      showAddprogrammePic: false,
      submiting: false,
      sortEle: null
    }
  },
  computed: {
    previewSrcList() {
      return this.list.map((v, i) => {
        return this.getImageUrl(v)
      })
    }
  },
  created() {

  },
  mounted() {
    this.$nextTick(() => {
      this.imageDrop()
    })
  },
  methods: {// 行拖拽排序
    imageDrop() {
      const el = document.querySelector('.pic-list')
      this.sortEle = Sortable.create(el, {
        disabled: false, // 是否禁用拖拽
        handle: '.pic-wrap', // 指定行可拖拽
        ghostClass: 'selected-highlight', // 拖拽样式
        animation: 300, // 拖拽延时
        // 拖拽开始
        onStart: (e) => {},
        // 拖拽移动
        onMove: (e) => {},
        // 拖拽结束
        onEnd: ({ item, from, newIndex, oldIndex }) => {
          if (newIndex === oldIndex) return
          const curObj = this.list[oldIndex] // 当前更新的图片
          const tmpObj = this.list[newIndex] // 占用位置的排序号
          let newSortNo = tmpObj.sort
          if (oldIndex < newIndex) {
            newSortNo = newIndex >= this.list.length - 1 ? newSortNo + 1 : this.list[newIndex + 1].sort
          }
          // const currRow = this.list.splice(oldIndex, 1)[0]
          // this.list.splice(newIndex, 0, currRow)

          // this.handleSort()
          // sortable.js已经将dom结构变成拖拽后的样子，需要先改回来=。=
          // removeNode(item)
          // insertNodeAt(from, item, oldIndex)

          const params = {
            id: curObj.id,
            newSortNo
          }
          updateImageSort(params).then(res => {
            if (res.success === 1) {
              this.refreshTable()
            }
          })
        }
      })
    },
    handleSort() {
      const params = this.imageList.map((v, index) => {
        return {
          id: v.id,
          newSortNo: index + 1
        }
      })
      updateImageSort(params).then(res => {
        if (res.success === 1) {
          this.refreshTable()
        }
      })
    },
    getImageUrl(v) {
      const imgHost = v.schemeId ? this.adsImgHost : this.sadImgHost
      return v.picUrl ? this.formatImageUrl(v.picUrl, imgHost) : ''
    },
    // 上传本地图片base64
    getLocalImageBase(base64) {
      // console.log('上传本地图片base64', base64)
    },
    // 获取本地图片file
    getLocalImageFile(file) {
      // console.log('获取本地图片file', file)
      const data = new FormData()
      data.append('file', file)
      uploadFile(data).then(res => {
        if (res.success === 1 && res.data) {
          const d = res.data
          const imgs = [{
            imageUrl: d.url
          }]
          this.handleSaveSchemeImage(imgs)
        }
      })
    },
    // 保存方案中心图片
    handleSaveSchemeImage(imgList) {
      if (this.submiting) return
      const hasMainPic = this.list.some(v => [1, '1'].includes(v.isMainPic))
      const data = imgList.map((v, i) => {
        return {
          isMainPic: hasMainPic ? 0 : i === 0 ? 1 : 0,
          productCombinationId: this.combineId,
          schemeId: v.programmeId || '',
          picUrl: v.imageUrl || '',
          panoramicPicUrl: v.panoramaUrl || '' // 720全景地址
        }
      })
      this.submiting = true
      const loading = this.$loading({
        lock: true,
        text: '效果图正在保存...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      saveRendering(data).then(res => {
        if (res.success === 1) {
          this.$message.success('效果图添加成功')
          this.refreshTable()
        }
        this.submiting = false
        loading.close()
        this.$refs.schemeImg.closeDialog()
      }).catch(() => {
        this.submiting = false
        loading.close()
      })
    },
    handleSetCover(row) {
      const id = row.id
      this.$confirm('确定要将当当前所选效果图设置为封面图吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        setCoverImage(id).then(res => {
          if (res.success === 1) {
            this.$message.success('操作成功')
            this.refreshTable()
          }
        })
      })
    },
    handleDelete(row) {
      const id = row.id
      this.$confirm('确定要删除当前所选效果图吗？一旦删除，将无法恢复。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteRendering(id).then(res => {
          if (res.success === 1) {
            this.$message.success('操作成功')
            this.refreshTable()
          }
        })
      })
    },
    refreshTable() {
      this.$emit('refresh')
    }
  }
}

</script>
<style lang='scss' scoped>
.table-title{
  margin-top: 20px;
  margin-bottom: 10px;
  line-height: 1.5;
  display: flex;
  align-items: center;
  .c-red{
    color: #f00;
  }
  .title-btns{
    margin-left: 10px;
    display: flex;
    align-items: center;
  }
}
.pic-list{
  display: flex;
  flex-wrap: wrap;
  padding-left: 90px;
  .pic-wrap{
    position: relative;
    margin: 0 10px 10px 0;
    width: 150px;
    height: 150px;
    overflow: hidden;
    border: 1px solid #f2f2f2;
    background-color:#f2f2f2;
    box-sizing: border-box;
    .el-image{
      width: 100%;
      height: 100%;
    }
    .opt{
      position: absolute;
      z-index: 1;
      left:5px ;
      top: 5px;
      right: 5px;
      height: 24px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .tag,.btn-cover, .btn-del{
      padding: 0 10px;
      height: 24px;
      line-height:22px;
      border: 1px solid #3DC094;
      color: #3DC094;
      box-sizing: border-box;
      border-radius: 2px;
      background-color: #fff;
    }
    .btn-del{
      color: #666;
      border-color: #666;
    }
    .btn-cover,.btn-del{
      display: none;
    }
    &:hover{
      .btn-cover,.btn-del{
        display: block;
        cursor: pointer;
      }
    }

  }
}
</style>
